/**
 * @Module   : Wechat oauth Module
 * @Brief   : Process Wechat oauth
 */
let express = require('express');
let router = express.Router();
let request = require('request');
let AV = require('leancloud-storage');
let config = require('../config/config')
let superagent = require('superagent');


router.get('/get_openid',async function(req,res, next){
    let code = req.query.code;
    let url ='https://api.weixin.qq.com/sns/oauth2/access_token?appid='+config.APPID+'&secret='+config.SECRET+'&code='+code+'&grant_type=authorization_code';
    let results =await superagent.get(url);
    let body = JSON.parse(results.text);
    if(body.errcode){
        res.send({
            code: -1,
            msg: '获取失败',
        })
        return;
    }
    let access_token = body.access_token;
    let openid = body.openid;

    let infoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='+access_token+'&openid='+openid+'&lang=zh_CN';
    let infoResults =await superagent.get(infoUrl);
    console.log(infoResults.text);
    let userInfo = JSON.parse(infoResults.text);
    if(!userInfo && !userInfo.openid){
        res.send({
            code: -1,
            msg: '获取失败',
        })
        return;
    }
    let query = new AV.Query('UserInfo');
    query.equalTo('openid', openid);
    query.find().then(function (results) {
        if(results.length==0){
            let TodoFolder = AV.Object.extend('UserInfo');
            let todoFolder = new TodoFolder();
            todoFolder.set('openid',openid);
            todoFolder.set('nickname',userInfo.nickname);
            todoFolder.set('headimgurl',userInfo.headimgurl);
            todoFolder.save().then(function (todo) {
                res.send({
                    code: 100,
                    msg: '获取成功',
                    data: openid
                })
            }, function (error) {
                console.error(error);
            });
        }else {
            res.send({
                code: 100,
                msg: '获取成功',
                data: openid
            })
        }
    }, function (error) {
        res.send({
            code: -1,
            msg: '获取失败',
        })
    });
});
module.exports = router;